package com.rq.download_okhttp;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;

public class Downloader implements DownloadIntentService.DownloadListener {

    public Downloader autoInstall(Activity context) {
        this.autoInstall = true;
        this.context = context;
        DownloadUtil.setContext(context);
        return this;
    }

    public Downloader init(Activity context) {
        this.context = context;
        DownloadUtil.setContext(context);
        return this;
    }

    private static class Holder {
        private final static Downloader instance = new Downloader();
    }

    public static Downloader getInstance() {
        return Holder.instance;
    }

    private Downloader() {

    }

    private String saveName = "rq";
    private boolean autoInstall = false;
    private Activity context;

    @Override
    public void onProgress(int progress) {

    }


    public void check() {
        String save = SPDownloadUtil.getInstance().get("installPath", "");
        if (!TextUtils.isEmpty(save)) {
            new File(save).delete();
            SPDownloadUtil.getInstance().remove("installPath");
        }
    }

    @Override
    public void onCompleted(File file) {
        if (autoInstall) {
            String FileProviderName = context.getPackageName() + ".fileProvider";//provider
            SPDownloadUtil.getInstance().save("installPath", file.getPath());
            DownloadUtil.installApp(context, file, FileProviderName);
        }
    }

    @Override
    public void onError() {

    }

    public Downloader startDownload(Activity activity, String url) {
        activity.startService(DownloadIntentService.getTask(activity, url, saveName, this));
        return this;
    }

    public Downloader addDownloadListener(DownloadIntentService.DownloadListener loginController) {
        DownloadIntentService.addDownloadCallBack(loginController);
        return this;
    }

    public Downloader removeDownloadListener(DownloadIntentService.DownloadListener loginController) {
        DownloadIntentService.removeDownloadCallBack(loginController);
        return this;
    }

}
